package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.StoreMapper;
import com.example.crossborderecommerce.service.*;
import com.example.crossborderecommerce.service.IStoreService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仓库模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/store")
public class StoreController {
    @Resource
    IStoreService storeService;
    @Resource
    IAdminService adminService;

    @Resource
    IProductService productService;

    @Resource
    IStoreCommodityService storeCommodityService;

    @Resource
    StoreMapper storeMapper;

    /**
     * 添加仓库
     * @param store
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Store store) {
        boolean res = storeService.save(store);
        if(res) {
            return Result.success("添加仓库成功！");
        }
        return Result.error("添加仓库失败！");
    }

    /**
     * 获得店铺总数
     * @return
     */
    @GetMapping("/count")
    public Result count() {
        return Result.success(storeService.count());
    }

    /**
     * 查询所有仓库
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<Store> storeList = storeService.list();
        if(storeList != null) {
            return Result.success("查询所有仓库成功！", storeList);
        }
        return Result.error("查询所有仓库失败！");
    }

    /**
     * 根据仓库类型获得仓库列表
     * @param type
     * @return
     */
    @GetMapping("/findStoreByType")
    public Result findStoreByType(@RequestParam("type") String type) {
        List<Store> storeList = storeService.findStoreByType(type);
        if(storeList == null) {
            return Result.error("查询仓库失败！");
        }
        return Result.success("查询仓库成功！", storeList);
    }

    /**
     * 根据仓库id获取仓库信息
     * @param id
     * @return
     */
    @GetMapping("/findStoreById")
    public Result findStoreById(@RequestParam("id") String id) {
        Store store = storeService.getById(id);
        if(store == null) {
            return Result.error("查询仓库失败！");
        }
        Admin admin = adminService.getById(store.getAdminId());
        store.setAdminName(admin.getName());
        if(store.getStoreManagerId() != null) {
            Admin storeManager = adminService.getById(store.getStoreManagerId());
            store.setStoreManagerName(storeManager.getName());
        }
        return Result.success("查询仓库成功！", store);
    }

    /**
     * 分页查询所有的仓库
     * @param name
     * @param type
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String type,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize){
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        if(!type.isEmpty()) {
            queryWrapper.eq("type", type);
        }
        Page<Store> storePage = storeService.page(new Page<>(pageNum,pageSize), queryWrapper);
        List<Store> storeList = storePage.getRecords();
        for(Store store : storeList) {
            Admin admin = adminService.getById(store.getAdminId());
            store.setAdminName(admin.getName());
            if(store.getStoreManagerId() != null) {
                Admin storeManager = adminService.getById(store.getStoreManagerId());
                store.setStoreManagerName(storeManager.getName());
            }
        }
        Page<Store> newStorePage = new Page<>(pageNum, pageSize);
        newStorePage.setRecords(storeList);
        newStorePage.setTotal(storePage.getTotal());
        return Result.success("成功查询所有仓库！", newStorePage);
    }
    /**
     * 查询仓库对应的货物
     * @return
     */
    @GetMapping("/findStoreCommodityByStoreId")
    public Result findStoreCommodityByStoreId(@RequestParam(defaultValue = "-1") String storeId) {
        QueryWrapper<StoreCommodity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        List<StoreCommodity> storeCommodityList=storeCommodityService.list(queryWrapper);
        for(StoreCommodity storeCommodity:storeCommodityList){
            Product product=productService.getById(storeCommodity.getProductId());
            storeCommodity.setProductName(product.getName());
        }
        return Result.success(storeCommodityList);
    }
    /**
     * 导出仓库信息
     * @param name
     * @param type
     * @param response
     * @return
     */
    @GetMapping("exportStoreList")
    public Result exportStoreList(@RequestParam(defaultValue = "") String name,
                                         @RequestParam(defaultValue = "") String type,
                                         HttpServletResponse response) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        if(!type.isEmpty()) {
            queryWrapper.eq("type", type);
        }
        List<Store> storeList = storeService.list(queryWrapper);
        for(Store store : storeList) {
            Admin admin = adminService.getById(store.getAdminId());
            store.setAdminName(admin.getName());
            if(store.getStoreManagerId() != null) {
                Admin storeManager = adminService.getById(store.getStoreManagerId());
                store.setStoreManagerName(storeManager.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("仓库名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("仓库地址");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("负责人");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("创建人");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < storeList.size(); i++) {
            row = sheet.createRow(i + 1);
            Store store = storeList.get(i);
            row.createCell((short) 0).setCellValue(store.getId());
            row.createCell((short) 1).setCellValue(store.getName());
            row.createCell((short) 2).setCellValue(store.getAddress());
            row.createCell((short) 3).setCellValue(store.getStoreManagerName());
            row.createCell((short) 4).setCellValue(store.getAdminName());
            try {
                Date createTime = inputDateFormat.parse(store.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 5).setCellValue(outputDateFormat.format(createTime));
            } catch (ParseException e) {
                row.createCell((short) 5).setCellValue(store.getCreateTime().toString());
            }
        }
        String fileName = "exportStoreList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductBrandList");
    }
    /**
     * 删除一系列仓库
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> storeIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = storeService.removeByIds(storeIds);
        if(res) {
            return Result.success("删除仓库成功");
        }
        return Result.error("删除仓库失败！");
    }

    /**
     * 修改仓库
     * @param store
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Store store) {
        boolean res = storeService.saveOrUpdate(store);
        if (res) {
            return Result.success("修改仓库信息成功！");
        }
        return Result.error("修改仓库信息失败！");
    }
    /**
     * 删除一个仓库
     * @param store
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Store store) {
        boolean res = storeService.removeById(store);
        if(res) {
            return Result.success("删除仓库成功！");
        }
        return Result.error("删除仓库失败！");
    }
    /**
     * 查询产品属性中所有创建人
     * @return
     */
    @GetMapping("/findAdminsInStore")
    public Result findAdminsInStore() {
        List<Admin> adminList = storeService.findAdminsInStore();
        if(adminList == null) {
            return Result.error("获取管理员信息失败！");
        }
        return Result.success(adminList);
    }

    /**
     * 根据仓库类型获取仓库数量
     * @return
     */
    @GetMapping("/getStoreCountByType")
    public Result getStoreCountByType() {
        return Result.success(storeMapper.getStoreCountByType());
    }

}
